//
//  OCExampleViewController.m
//  JXPagerView
//
//  Created by jiaxin on 2018/8/27.
//  Copyright © 2018年 jiaxin. All rights reserved.
//

#import "LessonStudyPageViewController.h"
#import "LessonCenterViewController.h"
#import "LessonStudyItemViewController.h"
#import "LessonStudyMenuView.h"
#import "LessonStudyDateView.h"
#import "LessonSwitchingView.h"

#import "LessonUseageModel.h"


@interface LessonStudyPageViewController ()<LessonStudyMenuViewDelegate>

@property (nonatomic, strong) LessonStudyMenuView *categoryView;

@property (nonatomic, strong) LessonStudyDateView *dateView;
@property (nonatomic, strong) NSArray <NSString *> *titles;

@property (nonatomic,strong) UIImage *coverImg;
@property (nonatomic,assign) BOOL status;
@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,strong) UILabel *navTitleLb;
@property (nonatomic,strong) UIButton *backBtn;
@property (nonatomic,assign) CGFloat offsetY;

@property (nonatomic,strong)UIView *navView;


@property (nonatomic,strong)UIButton *noAccountView;

@property (nonatomic,strong)UIView *noDataView;
@property (nonatomic,strong)UIView *noDataCoverView;
@property (nonatomic,strong)UIButton *noDataBackBtn;
@property (nonatomic,strong)UILabel *noDataTitleLb;
@property (nonatomic,strong)UILabel *noDataContentLb;
@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UIButton *noDataLoginBtn;

@end

@implementation LessonStudyPageViewController


- (LessonStudyMenuView *)categoryView{
    if (!_categoryView) {
        _categoryView = [[LessonStudyMenuView alloc]initWithTitles:@[@"全部",@"语文",@"数学",@"英语"] selectedStatus:self.status];
        _categoryView.delegate = self;
    }
    return _categoryView;
}
- (LessonStudyDateView *)dateView{
    if (!_dateView) {
        _dateView = [[LessonStudyDateView alloc]init];
    }
    return _dateView;
}

- (UILabel *)navTitleLb{
    if (!_navTitleLb) {
        _navTitleLb = [[UILabel alloc]init];
        _navTitleLb.text = @"学习中心";
        _navTitleLb.textColor = RGBA(255,255, 255, 1);
        _navTitleLb.font = font(18);
    }
    return _navTitleLb;
}

- (UIImage *)coverImg{
    if (!_coverImg) {
        _coverImg = [UIImage imageNamed:@"course_study_cover"];
    }
    return _coverImg;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNeedsStatusBarAppearanceUpdate];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = YES;
    
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"学习中心" completeBlock:^{
            @zf_strongify(self)
            [self setNetworkNormalUI];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self setNetworkNormalUI];
    }
    
    [self registNote];
}

- (void)setNetworkNormalUI{
    if ([RPAppManager isLogin]) {
        [self setUI];
    }else{
        [self setupNoDataView];
    }
}


- (void)setUI{
    self.status = NO;
    _pagerView = [self preferredPagingView];
    self.pagerView.mainTableView.gestureDelegate = self;
    self.pagerView.isListHorizontalScrollEnabled = NO;
    self.pagerView.automaticallyDisplayListVerticalScrollIndicator = NO;
    self.pagerView.pinSectionHeaderVerticalOffset = kNavBarHeight;
    self.pagerView.frame = CGRectMake(0, 0,kScreenW, kScreenH);
    [self.view addSubview:self.pagerView];
   
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    [self.view addSubview:self.navView];

    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.backBtn setImage:[UIImage imageNamed:@"common_back_white_tag"] forState:UIControlStateNormal];
    [self.backBtn setImage:[UIImage imageNamed:@"common_close_tag"] forState:UIControlStateHighlighted];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    [self.navView addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navView).offset(16);
        make.bottom.equalTo(self.navView).offset(-8);
    }];
    [self.view addSubview:self.navTitleLb];
    [self.navTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.backBtn);
    }];
    // 设置学习时间卡片时间
    LessonUseageModel *model = [LessonUseageModel getUseage];
    [self.dateView updateData:model];
    
    
}

- (void)setupNoDataView{
    self.noDataView = [[UIView alloc]init];
    self.noDataView.backgroundColor = RGBA(248, 248, 248, 1);
    [self.view addSubview:self.noDataView];
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.noDataLoginBtn = [[UIButton alloc]init];
    [self.noDataLoginBtn setBackgroundImage:[UIImage imageNamed:@"course_login_tag"] forState:UIControlStateNormal];
    [self.noDataLoginBtn setBackgroundImage:[UIImage imageNamed:@"course_login_tag"] forState:UIControlStateHighlighted];
    [self.noDataLoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.noDataLoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.noDataLoginBtn.titleLabel.font = font(14);
    [self.noDataLoginBtn addTarget:self action:@selector(loginMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.noDataView addSubview:self.noDataLoginBtn];
    [self.noDataLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.noDataView).offset(44);
        make.centerX.equalTo(self.noDataView);
    }];
    
    self.noDataContentLb = [[UILabel alloc]init];
    self.noDataContentLb.text = @"请登录后查看学习情况哦～";
    self.noDataContentLb.textColor = RGBA(198, 198, 197, 1);
    self.noDataContentLb.font = font(12);
    self.noDataContentLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDataContentLb];
    [self.noDataContentLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.bottom.equalTo(self.noDataLoginBtn.mas_top).offset(-48);
    }];

    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"noData"]];
    [self.noDataView addSubview:self.noDataImgView];
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.bottom.mas_equalTo(self.noDataContentLb.mas_top).offset(-8);
    }];

    self.noDataCoverView = [[UIView alloc]init];
    self.noDataCoverView.backgroundColor = [UIColor whiteColor];
    [self.noDataView addSubview:self.noDataCoverView];
    [self.noDataCoverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.noDataView);
        make.top.equalTo(self.noDataView).offset(kNavStatusBarHeight);
        make.height.mas_equalTo(44);
    }];
    self.noDataTitleLb = [[UILabel alloc]init];
    self.noDataTitleLb.text = @"学习中心";
    self.noDataTitleLb.textColor = C35;
    self.noDataTitleLb.font = [UIFont boldSystemFontOfSize:18];
    [self.noDataCoverView addSubview:self.noDataTitleLb];
    
    [self.noDataTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.noDataCoverView);
    }];
    
    self.noDataBackBtn = [[UIButton alloc]init];
    [self.noDataBackBtn setImage:[UIImage imageNamed:@"common_close_tag"] forState:UIControlStateNormal];
    [self.noDataBackBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.noDataCoverView addSubview:self.noDataBackBtn];
    [self.noDataBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self.noDataCoverView);
        make.width.mas_equalTo(44);
    }];
    

    
    self.view.backgroundColor = RGBA(248, 248, 248, 1);
    self.pagerView.backgroundColor = RGBA(248, 248, 248, 1);
}
- (void)loginMethod{
    [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - registNote
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfo) name:@"updateUserInfoSource" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAboutQuestion:) name:@"updateAboutQuestionSource" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStudyPageListSource) name:@"updateStudyList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateStudyPageListProgress) name:@"updateStudyPageListProgress" object:nil];
}

- (void)updateUserInfo{
    [self setUI];
}
- (void)updateStudyPageListProgress{
    [self updateStudyPageListSource];
}

- (void)updateAboutQuestion:(NSNotification *)note{
    [self updateStudyPageListSource];
}
- (void)updateStudyPageListSource{
    NSArray *vcs = self.pagerView.validListDict.allValues;
    for (LessonStudyItemViewController *vc in vcs) {
        [vc refreshData];
    }
}

- (JXPagerView *)preferredPagingView {
    return [[JXPagerView alloc] initWithDelegate:self];
}

#pragma mark - JXPagerViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    
    return self.dateView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return 220;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return 90;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.categoryView;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    //和categoryView的item数量一致
    return 4;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    LessonStudyItemViewController *list = [[LessonStudyItemViewController alloc] initWithSubjectId:[NSString stringWithFormat:@"%ld",(long)index]status:self.status];
    list.searchArray = self.searchArray;
    return list;
}

- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView{
   
    self.offsetY = scrollView.contentOffset.y;
    
    [self setNeedsStatusBarAppearanceUpdate];
    
    [self.categoryView hideLine];
    
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
        
        UIView *barImageView = self.navigationController.navigationBar.subviews.firstObject;
        barImageView.alpha = 1;
        
        [self.dateView updateDateAlpha:1];
        
        self.navTitleLb.textColor = RGBA(255, 255,255,1);
        
        self.backBtn.highlighted = NO;
        
    }
    
    // 判断偏移量
    // 下拉
    if (scrollView.contentOffset.y > 0) {
        
//        if (scrollView.contentOffset.y >= (220 - kNavBarHeight)) {
//            scrollView.contentOffset = CGPointMake(0, (220 - kNavBarHeight));
//        }
        
        CGFloat alpha = scrollView.contentOffset.y * (1/110.0);
   
        CGFloat coverA =  1 - alpha;
        
        self.navTitleLb.textColor = RGBA(0, 0, 0, alpha);
        
        self.backBtn.highlighted = YES;
        
        if (alpha > 1) {
            [self.categoryView showLine];
        }
        
        [self.dateView updateDateAlpha:coverA];
        
    }
}


#pragma mark - JXPagerMainTableViewGestureDelegate

- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //禁止categoryView左右滑动的时候，上下和左右都可以滚动
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
#pragma mark - CourseStudyMenuViewDelegate

- (void)menuDidSelectAtIndex:(NSInteger)index{
    self.currentIndex = index;
    [self.pagerView.listContainerView.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
    [self.pagerView.listContainerView didClickSelectedItemAtIndex:index];
    
}
- (void)menuDidSelectClassAtIndex:(NSInteger)index{
    index = index == 0?1:index;
    LessonCenterViewController *centerVC = [[LessonCenterViewController alloc]initWithSeachArray:self.searchArray andCurrentIndex:index];
    [self.navigationController pushViewController:centerVC animated:YES];
}

- (void)menuSwitchWithTouchPoint:(CGPoint)point status:(BOOL)status{
    
    
    
    LessonSwitchingView *switchView = [[LessonSwitchingView alloc]initWithTitleArray:@[@"待学习",@"已学完"] touchPoint:point index:status?1:0];
    
        
    [switchView show];

    __weak typeof(self)weakSelf = self;
    switchView.done = ^(NSInteger index) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        
        strongSelf.status = index == 1;
      
        [strongSelf.categoryView updateStatus:strongSelf.status];
        
        NSArray  *vcs = strongSelf.pagerView.validListDict.allValues;
        
        for (LessonStudyItemViewController *vc in vcs) {
            [vc updateDateSourceWithStatus:strongSelf.status];
        }
    };
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}



- (UIStatusBarStyle)preferredStatusBarStyle {

    
    if (![RPAppManager isLogin]) {
        return UIStatusBarStyleDefault;
    }
    if (self.offsetY >= 20) {
        return UIStatusBarStyleDefault;
    }
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {

    return UIStatusBarAnimationNone;
}

@end



